#include "project_config.h"

#if (FDT_ENABLE == 1)
#include "qelib.h"
#include "qe_earlycon.h"
#include "libfdt/libfdt.h"
#include "dtb_blob_data.h"



static int check_compatible(const void *fdt, int nodeoffset, const char *target) 
{
    const char *compatible;
    int len;

    compatible = fdt_getprop(fdt, nodeoffset, "compatible", &len);
    if (!compatible || len <= 0) {
        return 0;
    }

    while (len > 0) {
        if (strcmp(compatible, target) == 0) {
            return 1;
        }
        int slen = strlen(compatible) + 1;
        compatible += slen;
        len -= slen;
    }

    return 0;
}

int fdt_find_nodes_by_compatible(const void *fdt, int startoffset, const char *target, 
    void (*callback)(const void *fdt, int offset))
{
    int offset;

    for (offset = fdt_first_subnode(fdt, startoffset);
         offset >= 0;
         offset = fdt_next_subnode(fdt, offset)) {

        if (check_compatible(fdt, offset, target)) {
            callback(fdt, offset);
        }

        int ret = fdt_find_nodes_by_compatible(fdt, offset, target, callback);
        if (ret >= 0) {
            return ret;
        }
    }

    return -1;
}

static qe_init int early_init(void)
{
	/* Check dtb */
    int ret = fdt_check_header(dtb_get_blob_data());
	qe_assert(ret == 0);

	/* Earlycon init */
    qe_earlycon_init(dtb_get_blob_data());

    /* Version Print */
    qe_printf("\r\n\r\n");
    qe_printf("%s\r\n", PROJECT_NAME);
    qe_printf("%s\r\n", PROJECT_VERSION);
    qe_printf("build %s %s\r\n", __DATE__, __TIME__);

    qe_dm_scan(dtb_get_blob_data());

	return 0;
}
QE_EARLY_EXPORT(early_init);

#endif
